package mark.tom.hawk;

import mark.tom.hawk.template.Converter;
import mark.tom.hawk.template.Parser;

import static mark.tom.hawk.template.Parser.TYPE_LIST;
import static mark.tom.hawk.template.Parser.TYPE_OBJECT;

/**
 * @Description: 默认的数据转换器  内部实现通过解析器实现
 * @Author: Tom.Shen
 * @Package: mark.tom.hawk
 * @Date: 2020/9/26
 * @Copyright: 版权归 Tom.Shen 所有
 */
final class HawkConverter implements Converter {

    private final Parser parser;

    HawkConverter(Parser parser) {
        Util.checkNull("Parser should not be null", parser);
        this.parser = parser;
    }

    @Override
    public <T> String toString(T value) {
        if (null == value) {
            return null;
        }
        return parser.toJson(value);
    }

    @Override
    public <T> T fromString(String value, DataInfo info) throws Exception {
        if (null == value) {
            return null;
        }
        Util.checkNull("data info", info);

        Class<?> keyType = info.keyClazz;

        switch (info.dataType) {
            case DataInfo.TYPE_OBJECT:
                return toObject(value, keyType);
            case DataInfo.TYPE_LIST:
                return toList(value, keyType);
            default:
                return null;
        }
    }

    private <T> T toObject(String json, Class<?> type) throws Exception {
        return parser.fromJson(json, type, TYPE_OBJECT);
    }

    private <T> T toList(String json, Class<?> type) throws Exception {
        return parser.fromJson(json, type, TYPE_LIST);
    }

}
